package com.feidee.data.email.util.mail;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RMailSender {
    private static Logger LOG = LoggerFactory.getLogger(RMailSender.class);
  /**
   * 以HTML格式发送邮件
   *
   * @param mailInfo 待发送的邮件信息
   * @throws Exception
   */
  public static void sendHtmlMail(RMailInfo mailInfo) throws Exception {
    RAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
      authenticator = new RAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    Session sendMailSession = Session.getInstance(pro, authenticator);

    Message mailMessage = new MimeMessage(sendMailSession);
    Address from = new InternetAddress(mailInfo.getFromAddress());
    mailMessage.setFrom(from);
    List<String> toAddress = mailInfo.getToAddress();
    if (toAddress != null && toAddress.size() != 0) {
      Address[] tos = new Address[toAddress.size()];
      for (int i = 0; i < tos.length; i++) {
        tos[i] = new InternetAddress(toAddress.get(i));
      }
      mailMessage.setRecipients(Message.RecipientType.TO, tos);
    }
    List<String> ccAddress = mailInfo.getCcAddress();
    if (ccAddress != null && ccAddress.size() != 0) {
      Address[] ccs = new Address[ccAddress.size()];
      for (int i = 0; i < ccs.length; i++) {
        ccs[i] = new InternetAddress(ccAddress.get(i));
      }
      mailMessage.setRecipients(Message.RecipientType.CC, ccs);
    }

    List<String> bccAddress = mailInfo.getBccAddress();
    if (bccAddress != null && bccAddress.size() != 0) {
      Address[] bccs = new Address[bccAddress.size()];
      for (int i = 0; i < bccs.length; i++) {
        bccs[i] = new InternetAddress(bccAddress.get(i));
      }
      mailMessage.setRecipients(Message.RecipientType.BCC, bccs);
    }

    mailMessage.setSubject(mailInfo.getSubject());
    mailMessage.setSentDate(new Date());
    Multipart mainPart = new MimeMultipart();
    BodyPart html = new MimeBodyPart();
    html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
    mainPart.addBodyPart(html);

    //增加图片cid
    List<Image> images = mailInfo.getImages();

    if (images != null) {
      for (Image image : images) {
        MimeBodyPart picPart = new MimeBodyPart();
        DataSource source = new URLDataSource(new URL(image.getUrl()));
        picPart.setDataHandler(new DataHandler(source));
        picPart.setHeader("Content-ID", "<" + image.getId() + ">");
        mainPart.addBodyPart(picPart);
      }
    }

    //添加附件
    List<File> attachFileNames = mailInfo.getAttachFileNames();
    if (attachFileNames != null && attachFileNames.size()>0) {
		for (File file : attachFileNames) {
			MimeBodyPart filePart = new MimeBodyPart();
	        DataSource sourceFile = new URLDataSource(new URL(file.getUrl()));
	        DataHandler dataHandler = new DataHandler(sourceFile);
	        filePart.setDataHandler(dataHandler);
	        try {
	            String[] fullNameArr = dataHandler.getName().split("/");
                filePart.setFileName(MimeUtility.encodeText(fullNameArr[fullNameArr.length-1]));
			} catch (UnsupportedEncodingException e) {
			    LOG.error("邮件添加附件失败：", e);
				throw new Exception(e);
			}
	        mainPart.addBodyPart(filePart);
		}
	}
    mailMessage.setContent(mainPart);
    Transport.send(mailMessage);
  }


  public static void main(String[] args) {
  }

}   
